﻿//===========================================================================================================================
// Cuberry - http://www.cuberry.net
// Copyright (c) 2012
// by Peacequare® - Amir Moussa
//===========================================================================================================================
// This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License 
// as published by the Free Software Foundation, either version 3 of the License, or any later version.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
// documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
// the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and 
// to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions 
// of the Software.
//
// This program is distributed in the hope that it will be useful.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
// CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
// DEALINGS IN THE SOFTWARE.
//
// See the GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.
//===========================================================================================================================

using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using P2.Cuberry.Framework.BOLBase;
using P2.Cuberry.Framework.Helper;
using P2.Cuberry.Framework.Helper.Configuration;
using P2.Cuberry.Framework.Security;
using P2.Cuberry.Modules.Framework.ModuleManager.DAL;


namespace P2.Cuberry.Modules.Framework.ModuleManager.BusinessEntities
{
    public class XConfigValidationMandatoryFields : BizObject, INotifyPropertyChanged
    {

        #region Constructors
        
        public XConfigValidationMandatoryFields()
        {
            Modified = false;
        }


        public XConfigValidationMandatoryFields(DAL.XConfigValidationMandatoryFields xConfigValidationMandatoryFields)
        {
            Load(xConfigValidationMandatoryFields);
            Modified = false;
        }

        #endregion

        #region Members

        public Module ParentModule { set; get; }

        private int _validationId = int.MinValue;
        public int ValidationId
        {
            get { return _validationId; }
            set
            {
                if (value != _validationId)
                {
                    _validationId = value;
                    Modified = true;
                }
            }
        }


        private string _fieldEntityName = string.Empty;
        public string FieldEntityName
        {
            get { return _fieldEntityName; }
            set
            {
                if (value != _fieldEntityName)
                {
                    _fieldEntityName = value;
                    Modified = true;
                }
            }
        }


        private string _fieldName = string.Empty;
        public string FieldName
        {
            get { return _fieldName; }
            set
            {
                if (value != _fieldName)
                {
                    _fieldName = value;
                    Modified = true;
                }
            }
        }


        private bool? _isMandatory = false;
        public bool? IsMandatory
        {
            get { return _isMandatory; }
            set
            {
                if (value != _isMandatory)
                {
                    _isMandatory = value;
                    Modified = true;
                }
            }
        }


        private bool? _isUnique = false;
        public bool? IsUnique
        {
            get { return _isUnique; }
            set
            {
                if (value != _isUnique)
                {
                    _isUnique = value;
                    Modified = true;
                }
            }
        }

        private bool? _isUniqueInCombination = false;
        public bool? IsUniqueInCombination
        {
            get { return _isUniqueInCombination; }
            set
            {
                if (value != _isUniqueInCombination)
                {
                    _isUniqueInCombination = value;
                    Modified = true;
                }
            }
        }


        private string _validationType = string.Empty;
        public string ValidationType
        {
            get { return _validationType; }
            set
            {
                if (value != _validationType)
                {
                    _validationType = value;
                    Modified = true;
                }
            }
        }

        private string _moduleName = string.Empty;
        public string ModuleName
        {
            get { return _moduleName; }
            set
            {
                if (value != _moduleName)
                {
                    _moduleName = value;
                    Modified = true;
                }
            }
        }
        #endregion

        #region Read operations

        public void Load(DAL.XConfigValidationMandatoryFields xConfigValidationMandatoryFields)
        {
            try
            {
                if (xConfigValidationMandatoryFields != null)
                {
                    this.ValidationId = xConfigValidationMandatoryFields.ValidationID;
                    this.ModuleName = xConfigValidationMandatoryFields.ModuleName;
                    this.FieldEntityName = xConfigValidationMandatoryFields.EntityName;
                    this.FieldName = xConfigValidationMandatoryFields.FieldName;
                    this.IsMandatory = xConfigValidationMandatoryFields.IsMandatory;
                    this.IsUnique = xConfigValidationMandatoryFields.IsUnique;
                    this.IsUniqueInCombination = xConfigValidationMandatoryFields.IsUniqueInCombination;
                    this.ValidationType = xConfigValidationMandatoryFields.ValidationType;

                    this.CreatedBy = xConfigValidationMandatoryFields.CreatedBy;
                    this.CreatedOn = xConfigValidationMandatoryFields.CreatedOn;
                    this.EditedBy = xConfigValidationMandatoryFields.EditedBy;
                    this.EditedOn = xConfigValidationMandatoryFields.EditedOn;

                    this.StatusID = P2.Cuberry.Framework.Helper.Workflows.WorkflowStatus.GetInitialStatus(this.EntityName).StatusID;
                    this.Timestamp = xConfigValidationMandatoryFields.TStamp;
                }
                else
                {
                    this.ModuleName = string.Empty;
                    this.FieldEntityName = string.Empty;
                    this.FieldName = string.Empty;
                    this.IsMandatory = false;
                    this.IsUnique = false;
                    this.IsUniqueInCombination = false;
                    this.ValidationType = string.Empty;

                    P2.Cuberry.Framework.Helper.Workflows.WorkflowStatus initStatus = P2.Cuberry.Framework.Helper.Workflows.WorkflowStatus.GetInitialStatus(this.EntityName);
                    this.StatusID = initStatus.StatusID;
                }
                Modified = false;
            }
            catch (System.Exception ex)
            {
                P2ExceptionHandler.LogException(ex, string.Format("{0}.{1}", this.GetType().Name, System.Reflection.MethodInfo.GetCurrentMethod().Name));
            }
        }

        protected P2TransactionMessage FillMyObject()
        {
            P2TransactionMessage tMsg = new P2TransactionMessage();

            try
            {
                string connectionString = ConfigurationSetUp.GetEntConnectionString("Business", Properties.Settings.Default.EntityResources);
                using (ModuleManagerDataContext db = new ModuleManagerDataContext(connectionString))
                {
                    var transactions = from tran in db.XConfigValidationMandatoryFields
                                       where tran.ValidationID == this._validationId 
                                       select tran;
                    if (transactions.Count() > 0)
                    {
                        foreach (var transaction in transactions)
                        {
                            Load(transaction);
                        }
                    }
                }

                tMsg.TransactionStatus = "green";
                tMsg.MessageText = "TMsg_FillMyObjectSuceeded";
            }
            catch (Exception ex) //AM:TC!!
            {
                tMsg.TransactionStatus = "red";
                tMsg.MessageText = "Error_Error";
                tMsg.MessageFreeText = ex.Message;
                P2ExceptionHandler.LogException(ex, string.Format("{0}.{1}", this.GetType().Name, System.Reflection.MethodInfo.GetCurrentMethod().Name));
            }

            this.MessageStack.Add(tMsg);
            return tMsg;
        }

        public static ObservableCollection<XConfigValidationMandatoryFields> GetXConfigValidationMandatoryFieldsForHeader(Module xMod, PropertyChangedEventHandler onChange)
        {
            try
            {
                ObservableCollection<XConfigValidationMandatoryFields> itemsCollection = new ObservableCollection<XConfigValidationMandatoryFields>();

                string connectionString = ConfigurationSetUp.GetEntConnectionString("Business", Properties.Settings.Default.EntityResources);
                using (ModuleManagerDataContext db = new ModuleManagerDataContext(connectionString))
                {
                    var xConfigValidationMandatoryFields = from tranItem in db.XConfigValidationMandatoryFields
                                        where tranItem.ModuleName == xMod.ModuleName
                                        select tranItem;
                    if (xConfigValidationMandatoryFields.Count() > 0)
                    {
                        foreach (var xConfigValidationMandatoryField in xConfigValidationMandatoryFields)
                        {
                            itemsCollection.Add(new XConfigValidationMandatoryFields(xConfigValidationMandatoryField) { ParentModule = xMod });
                        }
                    }
                }

                return itemsCollection;
            }
            catch (System.Exception ex) //AM:TC
            {
                P2ExceptionHandler.LogException(ex, string.Format("{0}.{1}", "XAppResources", System.Reflection.MethodInfo.GetCurrentMethod().Name));
                return null;
            }
        }

        #endregion

        #region Copy operations

        public XConfigValidationMandatoryFields GetCopy()
        {
            try
            {
                XConfigValidationMandatoryFields newItem = new XConfigValidationMandatoryFields();
                newItem.ParentModule = this.ParentModule;
                newItem.ModuleName = this.ModuleName;

                newItem.ValidationId = this.ValidationId;
                newItem.FieldEntityName = this.FieldEntityName;
                newItem.FieldName = this.FieldName;
                newItem.ValidationType = this.ValidationType;
                newItem.IsMandatory = this.IsMandatory;
                newItem.IsUnique = this.IsUnique;
                newItem.IsUniqueInCombination = this.IsUniqueInCombination;

                newItem.Timestamp = this.Timestamp;
                newItem.Modified = this.Modified;
                return newItem;
            }
            catch (System.Exception ex) //AM:TC
            {
                P2ExceptionHandler.LogException(ex, string.Format("{0}.{1}", this.GetType().Name, System.Reflection.MethodInfo.GetCurrentMethod().Name));
                return null;
            }
        }

        public void UpdateFrom(XConfigValidationMandatoryFields sourceItem)
        {
            try
            {
                this.ParentModule = sourceItem.ParentModule;
                this.ModuleName = sourceItem.ModuleName;

                this.ValidationId = sourceItem.ValidationId;
                this.FieldEntityName = sourceItem.FieldEntityName;
                this.FieldName = sourceItem.FieldName;
                this.ValidationType = sourceItem.ValidationType;
                this.IsMandatory = sourceItem.IsMandatory;
                this.IsUnique = sourceItem.IsUnique;
                this.IsUniqueInCombination = sourceItem.IsUniqueInCombination;

                this.Timestamp = sourceItem.Timestamp;
                this.Modified = sourceItem.Modified;
            }
            catch (System.Exception ex) //AM:TC
            {
                P2ExceptionHandler.LogException(ex, string.Format("{0}.{1}", this.GetType().Name, System.Reflection.MethodInfo.GetCurrentMethod().Name));
            }
        }

        #endregion

        #region Property Changed

        public event PropertyChangedEventHandler PropertyChanged;


        private void OnPropertyChanged(string propertyName)
        {
            PropertyChangedEventHandler Handler = PropertyChanged;
            if (Handler != null) Handler(this, new PropertyChangedEventArgs(propertyName));
        }


        public void OnAllPropertiesChanged()
        {
            OnPropertyChanged("ModuleName");
            OnPropertyChanged("FieldEntityName");
            OnPropertyChanged("FieldName");
            OnPropertyChanged("IsMandatory");
            OnPropertyChanged("IsUnique");
            OnPropertyChanged("IsUniqueInCombination");
            OnPropertyChanged("ValidationType");
        }

        #endregion

        #region Validator

        public override P2Validator Validator
        {
            get
            {
                if (_validator == null)
                {
                    _validator = new P2Validator(Properties.Settings.Default.ModuleName, this.EntityName, "ValidationID", this);
                }
                return _validator;
            }
        }

        #endregion

        public P2MessageStack InsertAndUpdate(ModuleManagerDataContext db)
        {
            P2MessageStack MessageStack = new P2MessageStack();

            try
            {
                if (string.IsNullOrEmpty(this.CreatedBy)) this.CreatedBy = User.Current.UserID;
                this.EditedBy = User.Current.UserID;
                DAL.XConfigValidationMandatoryFields editedItem;
                if (this.CreatedOn == null)
                {
                    editedItem = new DAL.XConfigValidationMandatoryFields()
                    {
                        ModuleName = this.ModuleName,
                        EntityName = this.FieldEntityName,
                        FieldName = this.FieldName,
                        ValidationType = this.ValidationType,
                        IsMandatory = this.IsMandatory,
                        IsUnique = this.IsUnique,
                        IsUniqueInCombination = this.IsUniqueInCombination,

                        CreatedBy = this.CreatedBy,
                        CreatedOn = DateTime.Now,
                        EditedBy = this.EditedBy,
                        EditedOn = DateTime.Now
                    };
                    db.AddToXConfigValidationMandatoryFields(editedItem);
                }
                else
                {
                    editedItem = (from ti in db.XConfigValidationMandatoryFields
                                  where ti.ModuleName == this.ModuleName && ti.EntityName == this.FieldEntityName && ti.FieldName == this.FieldName
                                  select ti).First();
                    if (editedItem.TStamp == this.Timestamp)
                    {
                        editedItem.ModuleName = this.ModuleName;
                        editedItem.EntityName = this.FieldEntityName;
                        editedItem.FieldName = this.FieldName;
                        editedItem.ValidationType = this.ValidationType;
                        editedItem.IsMandatory = this.IsMandatory;
                        editedItem.IsUnique = this.IsUnique;
                        editedItem.IsUniqueInCombination = this.IsUniqueInCombination;

                        editedItem.EditedBy = this.EditedBy;
                        editedItem.EditedOn = DateTime.Now;
                    }
                    else
                    {

                        MessageStack.Add(new P2TransactionMessage("red", P2Translator.GetResource("TMsg_PaymentNotUpdated")));
                    }
                }
            }
            catch (Exception ex) //AM:TC!!
            {
                MessageStack.Add(new P2TransactionMessage("red", P2Translator.GetResource("Error_Error")));
                P2ExceptionHandler.LogException(ex, string.Format("{0}.{1}", this.GetType().Name, System.Reflection.MethodInfo.GetCurrentMethod().Name));
            }
            return MessageStack;
        }

        public void Delete(ModuleManagerDataContext db)
        {
            if (this.FieldName != String.Empty)
            {
                var item = (from ti in db.XConfigValidationMandatoryFields
                            where this.FieldName == ti.FieldName
                            select ti).First();
                db.DeleteObject(item);
                db.SaveChanges();
            }
        }

    }
}
